﻿using System.Linq;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Noria.Web.MyMSDN.Models;

namespace Noria.Web.MyMSDN
{
    /// <summary>
    /// Summary description for locale
    /// </summary>
    public class LocaleHandler : IHttpHandler
    {
        private static object _sync = new object();

        public void ProcessRequest(HttpContext context)
        {
            var payload = context.Cache["locale"] as string;
            if (payload == null)
            {
                lock (_sync)
                {
                    if (context.Cache["locale"] == null)
                    {
                        using (var db = new MmContext())
                        {
                            var locales = db.Locales.Where(p => p.Enabled).OrderBy(p => p.DisplayName).ToArray();
                            var obj = new JObject();

                            foreach (var locale in locales)
                            {
                                if (locale.Code == "__")
                                    locale.Code = "mu";

                                obj[locale.Code] = locale.DisplayName;
                            }

                            payload = obj.ToString(Formatting.None);
                            context.Cache["locale"] = payload;
                        }
                    }
                }
            }

            context.Response.ContentType = "application/json";
            context.Response.Write(payload);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}